import classService from '@/services/classService'; // 稍后创建这个服务文件
import { ElMessage } from 'element-plus';

const state = {
  // 根据不同角色存储的班级列表
  adminClassList: [],
  teacherClassList: [],
  studentClassList: [],
  currentClassDetail: null, // 当前查看的班级详情
  currentClassStudents: { // 当前班级的学生列表（带分页）
    records: [],
    total: 0,
    size: 10,
    current: 1,
    pages: 0
  },
  currentClassStats: null, // 当前班级统计信息
  currentInviteCode: null, // 当前生成的邀请码信息
  isLoading: false,
  error: null,
};

const getters = {
  // 根据登录用户角色选择合适的班级列表
  getClassList: (state, getters, rootState, rootGetters) => {
    if (rootGetters.isAdmin) return state.adminClassList;
    if (rootGetters.isTeacher) return state.teacherClassList;
    if (rootGetters.isAuthenticated) return state.studentClassList; // 普通登录用户视为学生
    return [];
  },
  getCurrentClassDetail: (state) => state.currentClassDetail,
  getCurrentClassStudents: (state) => state.currentClassStudents,
  getCurrentClassStats: (state) => state.currentClassStats,
  getCurrentInviteCode: (state) => state.currentInviteCode,
  isClassLoading: (state) => state.isLoading,
  getClassError: (state) => state.error,
};

const mutations = {
  SET_LOADING(state, isLoading) {
    state.isLoading = isLoading;
    state.error = null; // 开始加载时清除错误
  },
  SET_ERROR(state, error) {
    state.error = error;
    state.isLoading = false; // 出错时停止加载
  },
  SET_ADMIN_CLASS_LIST(state, classes) {
    state.adminClassList = classes;
  },
  SET_TEACHER_CLASS_LIST(state, classes) {
    state.teacherClassList = classes;
  },
  SET_STUDENT_CLASS_LIST(state, classes) {
    state.studentClassList = classes;
  },
  SET_CURRENT_CLASS_DETAIL(state, classDetail) {
    state.currentClassDetail = classDetail;
  },
  CLEAR_CURRENT_CLASS_DETAIL(state) {
    state.currentClassDetail = null;
    state.currentClassStudents = { records: [], total: 0, size: 10, current: 1, pages: 0 };
    state.currentClassStats = null;
    state.currentInviteCode = null;
  },
  UPDATE_CLASS_IN_LISTS(state, updatedClass) {
      const updateList = (list) => {
          const index = list.findIndex(c => c.id === updatedClass.id);
          if (index !== -1) {
              list.splice(index, 1, updatedClass);
          }
      };
      updateList(state.adminClassList);
      updateList(state.teacherClassList);
      updateList(state.studentClassList);

      // 更新详情页（如果当前正在查看）
      if (state.currentClassDetail && state.currentClassDetail.id === updatedClass.id) {
          state.currentClassDetail = updatedClass;
      }
  },
  REMOVE_CLASS_FROM_LISTS(state, classId) {
       const removeFromList = (list) => {
          const index = list.findIndex(c => c.id === classId);
          if (index !== -1) {
              list.splice(index, 1);
          }
      };
      removeFromList(state.adminClassList);
      removeFromList(state.teacherClassList);
      removeFromList(state.studentClassList);

       // 如果删除的是当前查看的班级，清除详情
      if (state.currentClassDetail && state.currentClassDetail.id === classId) {
           mutations.CLEAR_CURRENT_CLASS_DETAIL(state);
      }
  },
  SET_CURRENT_CLASS_STUDENTS(state, studentData) {
      // 使用 JSON.stringify 查看完整结构，防止对象过大被折叠
      // console.log("Mutation SET_CURRENT_CLASS_STUDENTS received payload:", JSON.stringify(studentData, null, 2)); // 移除日志
      // 确保 studentData 是一个对象，并且包含 records 数组
      if (studentData && typeof studentData === 'object' && Array.isArray(studentData.records)) {
           state.currentClassStudents = studentData;
      } else {
           console.error("SET_CURRENT_CLASS_STUDENTS received invalid payload, resetting state.", studentData);
           // 如果接收到的数据结构不对，重置为初始空状态
           state.currentClassStudents = { records: [], total: 0, size: 10, current: 1, pages: 0 };
      }
  },
  REMOVE_STUDENT_FROM_CURRENT(state, studentId) {
      state.currentClassStudents.records = state.currentClassStudents.records.filter(s => s.id !== studentId);
      state.currentClassStudents.total--;
      // 可能需要重新计算页数等，这里简化处理
  },
  SET_CURRENT_CLASS_STATS(state, stats) {
      state.currentClassStats = stats;
  },
  SET_CURRENT_INVITE_CODE(state, inviteInfo) {
      // console.log("Mutation SET_CURRENT_INVITE_CODE received payload:", JSON.stringify(inviteInfo, null, 2)); // 移除日志
      // 简单校验，确保是包含 inviteCode 的对象
      if (inviteInfo && typeof inviteInfo === 'object' && inviteInfo.inviteCode) {
            state.currentInviteCode = inviteInfo;
      } else {
          console.error("SET_CURRENT_INVITE_CODE received invalid payload:", inviteInfo);
          state.currentInviteCode = null; // 数据无效则清空
      }
  },
};

const actions = {
  // 根据角色获取班级列表
  async fetchClassList({ commit, rootGetters }) {
    commit('SET_LOADING', true);
    try {
      let response;
      if (rootGetters.isAdmin) {
        response = await classService.getAllClasses();
        // 检查返回结构并提交正确的数组
        if (response.data && response.data.success && Array.isArray(response.data.data)) {
            commit('SET_ADMIN_CLASS_LIST', response.data.data);
        } else {
             console.error("Invalid data structure received from getAllClasses:", response.data);
             commit('SET_ADMIN_CLASS_LIST', []); // 出错或结构不对时设置为空数组
        }
      } else if (rootGetters.isTeacher) {
        response = await classService.getTeacherClasses();
        // 检查返回结构并提交正确的数组
        if (response.data && response.data.success && Array.isArray(response.data.data)) {
            commit('SET_TEACHER_CLASS_LIST', response.data.data);
        } else {
             console.error("Invalid data structure received from getTeacherClasses:", response.data);
             commit('SET_TEACHER_CLASS_LIST', []);
        }
      } else if (rootGetters.isAuthenticated) { // 假设普通用户是学生
        response = await classService.getStudentClasses();
        // 检查返回结构并提交正确的数组
        if (response.data && response.data.success && Array.isArray(response.data.data)) {
            commit('SET_STUDENT_CLASS_LIST', response.data.data);
        } else {
            console.error("Invalid data structure received from getStudentClasses:", response.data);
            commit('SET_STUDENT_CLASS_LIST', []);
        }
      } else {
         console.warn("User role not determined for fetching class list.");
         commit('SET_LOADING', false);
         return { success: false, message: "未知用户角色" };
      }
      commit('SET_LOADING', false);
      // 返回原始 response，以便调用处可能需要 success 标志
      return response.data; 
    } catch (error) {
      console.error("Error fetching class list:", error);
      commit('SET_ERROR', error.response?.data?.message || '获取班级列表失败');
      ElMessage.error(state.error); // 显示错误提示
      return { success: false, message: state.error };
    }
  },

  // 获取班级详情
  async fetchClassDetail({ commit }, classId) {
    commit('SET_LOADING', true);
    commit('CLEAR_CURRENT_CLASS_DETAIL'); // 获取前清除旧数据
    try {
      const response = await classService.getClassById(classId);
      // 检查返回结构，确保提交的是 data 字段中的对象
      if (response.data && response.data.success && response.data.data) {
          commit('SET_CURRENT_CLASS_DETAIL', response.data.data);
          commit('SET_LOADING', false);
          return { success: true, data: response.data.data }; // 返回成功状态和数据
      } else {
          const errorMsg = response.data?.message || '获取班级详情失败，数据结构无效';
          console.error("Invalid data structure received from getClassById:", response.data);
          commit('SET_ERROR', errorMsg);
          ElMessage.error(errorMsg);
          commit('SET_LOADING', false);
          return { success: false, message: errorMsg };
      }
    } catch (error) {
      console.error("Error fetching class detail:", error);
      const errorMsg = error.response?.data?.message || '获取班级详情失败';
      commit('SET_ERROR', errorMsg);
      ElMessage.error(errorMsg); // 在 catch 中也提示错误
      commit('SET_LOADING', false);
      return { success: false, message: errorMsg };
    }
  },

  // 创建班级 (教师)
  async createClass({ commit, dispatch }, classData) {
    commit('SET_LOADING', true);
    try {
      const response = await classService.createClass(classData);
      commit('SET_LOADING', false);
      // 检查 API 调用是否真的成功
      if (response.data && response.data.success) {
          ElMessage.success('班级创建成功');
          // 创建成功后，重新获取班级列表以保证数据最新
          await dispatch('fetchClassList'); 
          return { success: true, data: response.data.data }; // 返回成功状态和数据
      } else {
          const errorMsg = response.data?.message || '创建班级失败';
          ElMessage.error(errorMsg);
          commit('SET_ERROR', errorMsg);
          return { success: false, message: errorMsg };
      }
    } catch (error) {
      console.error("Error creating class:", error);
      commit('SET_ERROR', error.response?.data?.message || '创建班级失败');
      ElMessage.error(state.error);
      return { success: false, message: state.error };
    }
  },

  // 更新班级 (教师)
  async updateClass({ commit }, { id, classData }) {
    commit('SET_LOADING', true);
    try {
      const response = await classService.updateClass(id, classData);
      commit('UPDATE_CLASS_IN_LISTS', response.data); // 假设更新成功后返回更新后的班级信息
      commit('SET_LOADING', false);
      ElMessage.success('班级更新成功');
      return response;
    } catch (error) {
      console.error("Error updating class:", error);
      commit('SET_ERROR', error.response?.data?.message || '更新班级失败');
      ElMessage.error(state.error);
      return { success: false, message: state.error };
    }
  },

  // 删除班级 (教师)
  async deleteClass({ commit }, classId) {
    commit('SET_LOADING', true);
    try {
      const response = await classService.deleteClass(classId);
      commit('REMOVE_CLASS_FROM_LISTS', classId);
      commit('SET_LOADING', false);
      ElMessage.success('班级删除成功');
      return response;
    } catch (error) {
      console.error("Error deleting class:", error);
      commit('SET_ERROR', error.response?.data?.message || '删除班级失败');
      ElMessage.error(state.error);
      return { success: false, message: state.error };
    }
  },

  // 生成邀请码 (教师)
  async generateInviteCode({ commit }, classId) {
    commit('SET_LOADING', true); // 可以考虑使用独立的 loading 状态
    try {
      // console.log(`Action generateInviteCode: Requesting for classId=${classId}`); // 移除日志
      const response = await classService.generateInviteCode(classId);
      // console.log("Action generateInviteCode: API response received:", JSON.stringify(response.data, null, 2)); // 移除日志

      // 检查响应结构并提交 data 部分
      if (response.data && response.data.success && response.data.data && response.data.data.inviteCode) {
          // console.log("Action generateInviteCode: Committing SET_CURRENT_INVITE_CODE with valid data."); // 移除日志
          commit('SET_CURRENT_INVITE_CODE', response.data.data);
          commit('SET_LOADING', false);
          ElMessage.success('邀请码生成成功');
          return { success: true, data: response.data.data };
      } else {
          const errorMsg = response.data?.message || '生成邀请码失败，数据结构无效';
          console.error("Invalid data structure received from generateInviteCode:", response.data);
          commit('SET_ERROR', errorMsg);
          commit('SET_CURRENT_INVITE_CODE', null); // 清空旧的邀请码
          ElMessage.error(errorMsg);
          commit('SET_LOADING', false);
          return { success: false, message: errorMsg };
      }
    } catch (error) {
      console.error("Error generating invite code:", error);
      const errorMsg = error.response?.data?.message || '生成邀请码失败';
      commit('SET_ERROR', errorMsg);
      commit('SET_CURRENT_INVITE_CODE', null); // 出错时也清空
      ElMessage.error(errorMsg);
      commit('SET_LOADING', false);
      return { success: false, message: errorMsg };
    }
  },

  // 加入班级 (学生)
  async joinClassByCode({ commit, dispatch }, inviteCode) {
    commit('SET_LOADING', true);
    try {
      const response = await classService.joinClass(inviteCode);
      commit('SET_LOADING', false);

      if (response.data && response.data.success) {
        ElMessage.success(response.data.message || '成功加入班级');
        // 加入成功后刷新学生班级列表
        await dispatch('fetchClassList');
        return { success: true, data: response.data.data }; // 返回成功状态和班级数据
      } else {
         const errorMsg = response.data?.message || '加入班级失败';
         ElMessage.error(errorMsg);
         commit('SET_ERROR', errorMsg);
         return { success: false, message: errorMsg };
      }

    } catch (error) {
      console.error("Error joining class:", error);
      const errorMsg = error.response?.data?.message || '加入班级失败';
      commit('SET_ERROR', errorMsg);
      ElMessage.error(errorMsg);
      commit('SET_LOADING', false); 
      return { success: false, message: errorMsg };
    }
  },

  // 获取班级学生列表 (教师)
  async fetchClassStudents({ commit }, { classId, page = 1, size = 10, query = '' }) {
    // 注意：这里的 SET_LOADING 控制的是整个 class 模块的 loading，
    // ClassDetail 组件内部还有一个 studentsLoading 用于表格自身的加载状态
    // commit('SET_LOADING', true); // 暂时不设置全局 loading，让表格自己的 loading 生效
    try {
      // console.log(`Action fetchClassStudents: Fetching page=${page}, size=${size}, query='${query}' for classId=${classId}`); // 移除日志
      const response = await classService.getClassStudents(classId, page, size, query);
      // console.log("Action fetchClassStudents: API response received:", JSON.stringify(response.data, null, 2)); // 移除日志

      // 严格检查返回结构
      if (response.data && response.data.success && response.data.data && Array.isArray(response.data.data.records)) {
          // console.log("Action fetchClassStudents: Committing SET_CURRENT_CLASS_STUDENTS with valid data."); // 移除日志
          commit('SET_CURRENT_CLASS_STUDENTS', response.data.data); // 提交包含 records 的 pagination 对象
          // commit('SET_LOADING', false);
          return response.data; // 返回原始响应
      } else {
          const errorMsg = response.data?.message || '获取学生列表失败，数据结构无效';
          console.error("Invalid data structure received from getClassStudents:", response.data);
          commit('SET_ERROR', errorMsg);
          ElMessage.error(errorMsg);
          // 提交空结构
          commit('SET_CURRENT_CLASS_STUDENTS', { records: [], total: 0, size: size, current: page, pages: 0 });
          // commit('SET_LOADING', false);
          return { success: false, message: errorMsg };
      }
    } catch (error) {
      console.error("Error fetching class students:", error);
      const errorMsg = error.response?.data?.message || '获取学生列表失败';
      commit('SET_ERROR', errorMsg);
      ElMessage.error(errorMsg);
      // 发生错误时也提交空结构
      commit('SET_CURRENT_CLASS_STUDENTS', { records: [], total: 0, size: size, current: page, pages: 0 });
      // commit('SET_LOADING', false);
      return { success: false, message: errorMsg };
    }
  },

  // 添加学生到班级 (教师)
  async addStudentToClass({ commit, dispatch }, { classId, studentId }) {
    commit('SET_LOADING', true);
    try {
      const response = await classService.addStudent(classId, studentId);
      commit('SET_LOADING', false);
      if(response.success) {
          ElMessage.success('添加学生成功');
          // 成功后刷新学生列表
          await dispatch('fetchClassStudents', { classId }); // 使用默认分页
      } else {
          ElMessage.error(response.message || '添加学生失败');
      }
      return response;
    } catch (error) {
      console.error("Error adding student:", error);
      commit('SET_ERROR', error.response?.data?.message || '添加学生失败');
      ElMessage.error(state.error);
      return { success: false, message: state.error };
    }
  },

  // 从班级移除学生 (教师)
  async removeStudentFromClass({ commit, dispatch }, { classId, studentId }) {
    commit('SET_LOADING', true); // 考虑改为局部 loading 或移除全局 loading
    try {
      const response = await classService.removeStudent(classId, studentId);
      commit('SET_LOADING', false);

      if(response.data && response.data.success) { // 检查 response.data.success
          ElMessage.success(response.data.message || '移除学生成功'); // 可以使用后端返回的消息
          // 成功后刷新学生列表
          await dispatch('fetchClassStudents', { classId }); 
          return { success: true }; // 返回成功状态
      } else {
          const errorMsg = response.data?.message || '移除学生失败';
          ElMessage.error(errorMsg);
          commit('SET_ERROR', errorMsg); // 在失败时设置错误状态
          return { success: false, message: errorMsg };
      }

    } catch (error) {
      console.error("Error removing student:", error);
      const errorMsg = error.response?.data?.message || '移除学生失败';
      commit('SET_ERROR', errorMsg);
      ElMessage.error(errorMsg);
      commit('SET_LOADING', false); 
      return { success: false, message: errorMsg };
    }
  },

   // 获取班级统计信息 (教师)
  async fetchClassStatistics({ commit }, classId) {
    commit('SET_LOADING', true);
    try {
      const response = await classService.getClassStatistics(classId);
      // 再次确保只 commit data 部分
      if (response.data && response.data.success && response.data.data) {
          commit('SET_CURRENT_CLASS_STATS', response.data.data); 
          commit('SET_LOADING', false);
          return { success: true, data: response.data.data };
      } else {
          const errorMsg = response.data?.message || '获取统计信息失败，数据结构无效';
          console.error("Invalid data structure received from getClassStatistics:", response.data);
          commit('SET_ERROR', errorMsg);
          ElMessage.error(errorMsg);
          commit('SET_LOADING', false);
          return { success: false, message: errorMsg };
      }
    } catch (error) {
      console.error("Error fetching class statistics:", error);
      const errorMsg = error.response?.data?.message || '获取统计信息失败';
      commit('SET_ERROR', errorMsg);
      ElMessage.error(errorMsg);
      commit('SET_LOADING', false);
      return { success: false, message: errorMsg };
    }
  },
};

export default {
  namespaced: true, // 启用命名空间
  state,
  getters,
  mutations,
  actions
}; 